<?php

/**
 * templates actions.
 *
 * @package    master_directory
 * @subpackage templates
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class templatesActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
  	$this->form = new TemplateForm();
  	
  //	$this->master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
  
  	$directory_id = $this->getUser()->getAttribute("directory_id");
  	
  	$this->directory = Doctrine_Core::getTable('MasterDirectory')->find($directory_id);
  	
    $this->selected_directory = $directory_id;
    
    //$this->templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplates();
    $this->templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplatesByDirectory($this->selected_directory);
    
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($this->selected_directory);

    $this->categories = $this->getCategoriesWithLevels($all_categories);
    
    $this->levelIds =  array();
    
    $sorting_criterias = Doctrine_Core::getTable('RatingSorting')->getAllCriterias();
    
    $this->sorting_criterias = $sorting_criterias;

  }
  
  public function executeLoadDirectoryData(sfWebRequest $request){
  	
  	$directory_id = $this->getUser()->getAttribute("directory_id");
  	
  	$form = new TemplateForm();
  	
  	//$master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
  	
  	$directory = Doctrine_Core::getTable('MasterDirectory')->find($directory_id);
  	
    //$templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplates();
    $templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplatesByDirectory($directory_id);
    
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);

    $categories = $this->getCategoriesWithLevels($all_categories);
    
    $selected_directory = $directory_id;
    
    $this->getUser()->setAttribute('selected_directory',$directory_id);
    
    $sorting_criterias = Doctrine_Core::getTable('RatingSorting')->getAllCriterias();
    
    return $this->renderPartial('template_super_container',array('form'=>$form, 'directory' => $directory, 'selected_directory' => $directory_id, 'categories'=> $categories, 'levelIds' => array(), 'templates' => $templates, 'sorting_criterias' => $sorting_criterias));
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->template = Doctrine_Core::getTable('Template')->find(array($request->getParameter('id')));
    
    $this->forward404Unless($this->template);

    $templatesToLevel = Doctrine_Core::getTable('Template2Level')->getTemplatesLevelsByTemplateId($this->template->getId());
    
    $home_directory = $this->template->getMasterDirectory();
    
    $directory_id = $this->getUser()->getAttribute("directory_id");
    
    $directory = Doctrine_Core::getTable('MasterDirectory')->find($directory_id);
    //$directory_id = $templatesToLevel[0]->getLevel()->getCategory()->getMasterDirectory()->getId() != "" ? $templatesToLevel[0]->getLevel()->getCategory()->getMasterDirectory()->getId() : $home_directory[0]->getId();
    
  	$form = new TemplateForm($this->template);
  	
  //	$master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
  
  	
  	
    $templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplatesByDirectory($directory_id) ;
    
    
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);

    $categories = $this->getCategoriesWithLevels($all_categories);
    
    
    //$categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    
    $selected_directory = $directory_id;
    
    $levelIds =  array();   
    
    foreach ($templatesToLevel as $template2level){
    	array_push($levelIds, $template2level->getLevelId());
    }
    
	$sorting_criterias = Doctrine_Core::getTable('RatingSorting')->getAllCriterias();
	
    return $this->renderPartial ('template_super_container', array('form' => $form, 'directory' => $directory, 'selected_directory' => $selected_directory, 'categories' => $categories, 'levelIds' => $levelIds,'templates' => $templates, 'sorting_criterias' => $sorting_criterias));
    
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new TemplateForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

	$form = new TemplateForm();
    
    $this->processForm($request, $form);
    
    $directory_id = $request->getParameter('directory_id');
    
    $directory = Doctrine_Core::getTable('MasterDirectory')->find(array($directory_id));
    
    if ($directory->getTemplate() != null && $this->getRequestParameter("chb_home_page")){
    	$directory->setTemplate($form->getObject());
    	$directory->save();
    }
    
    //$this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);

    $this->categories = $this->getCategoriesWithLevels($all_categories);
    
    //echo '$form->getObject()->getId(): ' . $form->getObject()->getId(); exit();
    
    foreach ($this->categories as $category) {
    	
    	$root_level = Doctrine_Core::getTable('Level')->getRootLevel($category->getId());
       	$the_table = Doctrine_Core::getTable('Level');
       	$the_table->setChildren();
       	$the_table->getCategoryChildrenList($root_level);
       	foreach ($the_table->getChildren() as $level) {
       		
       		if($request->getParameter('check_'.$level->getId())){
				Doctrine_Core::getTable('Template2Level')->saveMainLevel($level, $form->getObject()->getId(), $category);
       		}
   		}
    }
    
    $this->selected_directory = $directory_id;
    

    $this->form = new TemplateForm();
    
    //$master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
    
    //$templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplates();
    
    $templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplatesByDirectory($directory_id);
    
    $this->getUser()->setFlash('saved_flash', 'Object saved',false);
    
	$action_str = "Template created ID: " . $form->getObject()->getId();
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));    
  	
  	$sorting_criterias = Doctrine_Core::getTable('RatingSorting')->getAllCriterias();
    
    return $this->renderPartial('template_super_container',array('form'=>$this->form, 'directory' => $directory, 'selected_directory' => $directory_id, 'categories'=> $this->categories, 'levelIds' => array(), 'templates' => $templates, 'sorting_criterias' => $sorting_criterias));
  }
  
  

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($template = Doctrine_Core::getTable('Template')->find(array($request->getParameter('id'))), sprintf('Object template does not exist (%s).', $request->getParameter('id')));
    $this->form = new TemplateForm($template);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($template = Doctrine_Core::getTable('Template')->find(array($request->getParameter('id'))), sprintf('Object template does not exist (%s).', $request->getParameter('id')));
    $form = new TemplateForm($template);

    $directory_id = $request->getParameter('directory_id');
    
    $directory = Doctrine_Core::getTable('MasterDirectory')->find(array($directory_id));
    
    $this->processForm($request, $form);

    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    $this->categories = $this->getCategoriesWithLevels($all_categories);
     
    $marked_levels = array();
    
    $marked_ids = array();
    
    foreach ($this->categories as $category) {
    	
    	$root_level = Doctrine_Core::getTable('Level')->getRootLevel($category->getId());
       	$the_table = Doctrine_Core::getTable('Level');
       	$the_table->setChildren();
       	$the_table->getCategoryChildrenList($root_level);
       	foreach ($the_table->getChildren() as $level) {
       		
       		if($request->getParameter('check_'.$level->getId())){
				array_push($marked_levels, $level);
				array_push($marked_ids, $level->getId());
       		}
       	     		
   		}
    }    
    
    //existing levels
   
    $template2levels = Doctrine_Core::getTable('Template2Level')->getTemplatesLevelsByTemplateId($template->getId());
    
    $existing_levels = array();
    
    foreach ($template2levels as $existing_template2level){
    	array_push($existing_levels, $existing_template2level->getLevelId());
    }
    

    
    
    if (count($existing_levels) != count($marked_ids) || count(array_intersect($existing_levels, $marked_ids))  != count($existing_levels)){
    	
    	//echo 'hay q eliminar'; exit();
    	//delete contents and 
    	$template_contents = Doctrine_Core::getTable('TemplateContent')->getTemplateContentByTemplateId($template->getId());
    	foreach ($template_contents as $template_content){
    		$template_content->delete();
    	}
    	
    	$template->setFooterId(null);
    	//$template->save();
    	
    	//delete templates whose's footer is the current modified template
    	$templates_footer_involved = Doctrine_Core::getTable('Template')->getTemplatesWithTemplateFooter($template->getId());
    	foreach ($templates_footer_involved as $template_footer_involved){
    		$template_footer_involved->setFooterId(null);
    		$template_footer_involved->save();
    	}
    	 $this->getUser()->setFlash('alert_flash', 'Need to create content and footer',false);
    }
    
    Doctrine_Core::getTable('Template2Level')->deleteTemplate2Levels($form->getObject()->getId());
    
    
    //$this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    
    
    /*foreach ($this->categories as $category) {
    	
    	$root_level = Doctrine_Core::getTable('Level')->getRootLevel($category->getId());
       	$the_table = Doctrine_Core::getTable('Level');
       	$the_table->setChildren();
       	$the_table->getCategoryChildrenList($root_level);
       	foreach ($the_table->getChildren() as $level) {
       		
       		if($request->getParameter('chbx_level_'.$level->getId())){
				Doctrine_Core::getTable('Template2Level')->saveMainLevel($level, $form->getObject()->getId(), $category);
       		}
   		}
    }*/
    	foreach ($marked_levels as $level) {
				Doctrine_Core::getTable('Template2Level')->saveMainLevel($level, $form->getObject()->getId(), Doctrine_Core::getTable('Category')->find(array($level->getCategoryId())));
    		
    	}
    
    
    $this->selected_directory = $directory_id;
    

    $this->form = new TemplateForm();
    
    $master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
    
    $templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplatesByDirectory($directory_id);
    
        
    $this->getUser()->setFlash('saved_flash', 'Object saved',false);
    
	$action_str = "Template updated ID: " . $form->getObject()->getId();
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));    
  	
  	$sorting_criterias = Doctrine_Core::getTable('RatingSorting')->getAllCriterias();
    
    return $this->renderPartial('template_super_container',array('form'=>$this->form, 'directory' => $directory, 'selected_directory' => $directory_id, 'categories'=> $this->categories, 'levelIds' => array(), 'templates' => $templates, 'sorting_criterias' => $sorting_criterias));    
    
  }

  public function executeDelete(sfWebRequest $request)
  {
    //$request->checkCSRFProtection();

    $this->forward404Unless($template = Doctrine_Core::getTable('Template')->find(array($request->getParameter('id'))), sprintf('Object template does not exist (%s).', $request->getParameter('id')));
    //$template->delete();
    
    $template->setDeleted(1);
    $template->save();
    
    $directories = $template->getMasterDirectory();
    
    if (count($directories) > 0){
    	//un home
    	$directory = $directories[0];
    	$directory->setHomeTemplateId(null);
    	$directory->save();
    }
    else{
   	  	//get the directory by the template
	  	$template2levels = Doctrine_Core::getTable('Template2Level')->getTemplatesLevelsByTemplateId($template->getId());
	  	
	  	$level = $template2levels[0]->getLevel();
	  	
	  	$category = $level->getCategory();
	  	
	  	$directory = $category->getMasterDirectory();
    }
   
    $directory_id = $directory->getId();
    
    Doctrine_Core::getTable('Template2Level')->logicalDeleteTemplate2Levels($template->getId());
    
    $form = new TemplateForm();
  	
  //	$master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
  	
  	$directory = Doctrine_Core::getTable('MasterDirectory')->find(array($directory_id));
  	
    //$templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplates();
    
  	$templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplatesByDirectory($directory->getId());
    
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory->getId());

    $this->categories = $this->getCategoriesWithLevels($all_categories);
    
    $selected_directory = $directory->getId();
    
	$action_str = "Template deleted ID: " . $template->getId();
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));      
  	
  	$sorting_criterias = Doctrine_Core::getTable('RatingSorting')->getAllCriterias();
    
    return $this->renderPartial('template_super_container',array('form'=>$form, 'directory' => $directory, 'selected_directory' => $selected_directory, 'categories'=> $this->categories, 'levelIds' => array(), 'templates' => $templates, 'sorting_criterias' => $sorting_criterias));

    //$this->redirect('templates/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
   /* if ($form->isValid())
    {
      $template = $form->save();

      //$this->redirect('templates/edit?id='.$template->getId());
    }*/
    
     $template = $form->save();
  }
  
  protected function getCategoriesWithLevels($all_categories){
    $categories_with_levels = array();
    
    foreach ($all_categories as $a_category){
    	if (count($a_category->getLevel()) > 0){
    		array_push($categories_with_levels, $a_category);
    	}
    }
    return $categories_with_levels;
  }
  
}
